package juc.blockqueue.arrayblockqueue;

/**
 * @ClassName ArrayBlockingQueueExample
 * @PackageName juc.blockqueue
 * @projectName myThread
 * @Description 
 * @Author games
 * @Date 2025/9/4 上午10:09
 * @Version 1.0
 */
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * ArrayBlockingQueue 是一个基于数组实现的有界阻塞队列，它具有以下典型使用场景：
 * 主要特点
 * 有界容量：创建时需要指定固定容量，队列大小不可变
 * 阻塞特性：
 * 当队列满时，插入操作会被阻塞
 * 当队列空时，取出操作会被阻塞
 * 线程安全：内部使用可重入锁保证线程安全
 */


public class MultipleProducerConsumer {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);

        // 创建多个生产者
        for (int i = 1; i <= 2; i++) {
            final int producerId = i;
            new Thread(() -> {
                try {
                    for (int j = 1; j <= 3; j++) {
                        String item = "Producer" + producerId + "-Item" + j;
                        queue.put(item);
                        System.out.println("Produced: " + item);
                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }).start();
        }

        // 创建多个消费者
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                try {
                    while (true) {
                        String item = queue.take();
                        System.out.println("Consumer" + Thread.currentThread().getName()
                                + " consumed: " + item);
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }).start();
        }

        //Thread.sleep(10000); // 运行10秒后结束
    }
}

